package com.mobile.ado.setting.calendar;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;

import android.app.Activity;
import android.content.Intent;
import android.view.MotionEvent;
import android.view.GestureDetector.OnGestureListener;

public class CalendarGestureListener implements OnGestureListener {

	private Activity activity;
	private CalendarView calendarView;
	private Calendar calendar;
	private ArrayList<DateRec> dateRecList;

	public static final int INVALID_POSITION = -1;

	public CalendarGestureListener(Activity activity,
			CalendarView calenderView, Calendar calendar,
			ArrayList<DateRec> dateRecList) {
		this.activity = activity;
		this.calendar = calendar;
		this.calendarView = calenderView;
		this.dateRecList = dateRecList;
	}

	@Override
	public boolean onSingleTapUp(MotionEvent paramMotionEvent) {
		float eventX = paramMotionEvent.getX();
		float eventY = paramMotionEvent.getY();

		int day = getDay(eventX, eventY);
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH) + 1;
		Intent intent = new Intent(activity, MessageScheduleActivity.class);
		intent.putExtra("selectedDay", new GregorianCalendar(year, month, day));
		activity.startActivity(intent);
		return true;
	}

	@Override
	public void onShowPress(MotionEvent paramMotionEvent) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onScroll(MotionEvent paramMotionEvent1,
			MotionEvent paramMotionEvent2, float paramFloat1, float paramFloat2) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onLongPress(MotionEvent paramMotionEvent) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onFling(MotionEvent paramMotionEvent1,
			MotionEvent paramMotionEvent2, float paramFloat1, float paramFloat2) {

		if (paramMotionEvent1.getX() > paramMotionEvent2.getX()) {
			calendar.add(Calendar.MONTH, 1);
			calendarView.invalidate();
		}

		if (paramMotionEvent1.getX() < paramMotionEvent2.getX()) {
			calendar.add(Calendar.MONTH, -1);
			calendarView.invalidate();
		}

		return true;

	}

	@Override
	public boolean onDown(MotionEvent paramMotionEvent) {
		// TODO Auto-generated method stub
		return false;
	}

	private int getDay(float x, float y) {
		for (DateRec rect : dateRecList) {
			if (rect.isSelected(x, y)) {
				return rect.getDay();
			}
		}
		return INVALID_POSITION;
	}
}
